#include "cpuSimulator.h"
#include "interruptManager.h"
#include "systemCallHandler.h"
#include <QDebug>
#include <QRegularExpression>
#include <QMutexLocker>
#include <QTimer>

// 静态成员初始化
const QStringList CpuSimulator::REGISTER_NAMES = {
    "AX", "BX", "CX", "DX", "EX", "FX",  // 通用寄存器
    "SI", "DI", "R1", "R2",              // 索引寄存器
    "BP", "SP", "IP", "FLAGS"            // 特殊寄存器
};

/**
 * @brief CpuSimulator构造函数
 * @param parent 父对象指针
 */
CpuSimulator::CpuSimulator(QObject *parent)
    : QObject(parent)
    , currentState(CpuState::Stopped)
    , instructionPointer(0)
    , halted(false)
    , interruptManager(nullptr)
    , executionTimer(new QTimer(this))
{
    initializeRegisters();
    initializeMemory();
    
    // 设置执行计时器
    executionTimer->setSingleShot(false);
    executionTimer->setInterval(1); // 1毫秒间隔
    connect(executionTimer, &QTimer::timeout, this, &CpuSimulator::executeNextInstruction);
}

/**
 * @brief CpuSimulator析构函数
 */
CpuSimulator::~CpuSimulator()
{
    // 智能指针和Qt对象会自动清理
}

/**
 * @brief 加载汇编程序
 * @param assemblyCode 汇编代码文本
 * @return bool 加载是否成功
 */
bool CpuSimulator::loadProgram(const QString& assemblyCode)
{
    // 重置CPU状态（在锁外调用，避免死锁）
    resetCpu();
    
    QMutexLocker locker(&cpuMutex);
    
    // 解析汇编代码
    if (!parseAssemblyCode(assemblyCode)) {
        emit errorOccurred("汇编代码解析失败");
        return false;
    }
    
    currentState = CpuState::Stopped;
    emit stateChanged(currentState);
    
    return true;
}

/**
 * @brief 开始执行程序
 * @return bool 执行是否成功开始
 */
bool CpuSimulator::executeProgram()
{
    QMutexLocker locker(&cpuMutex);
    
    if (instructions.isEmpty()) {
        emit errorOccurred("没有加载程序");
        return false;
    }
    
    currentState = CpuState::Running;
    emit stateChanged(currentState);
    
    // 启动计时器进行非阻塞执行
    executionTimer->start();
    
    return true;
}

/**
 * @brief 单步执行
 * @return bool 单步执行是否成功
 */
bool CpuSimulator::stepExecution()
{
    QMutexLocker locker(&cpuMutex);
    
    if (instructionPointer >= instructions.size()) {
        currentState = CpuState::Stopped;
        emit stateChanged(currentState);
        return false;
    }
    
    if (halted) {
        currentState = CpuState::Halted;
        emit stateChanged(currentState);
        return false;
    }
    
    const Instruction& instruction = instructions[instructionPointer];
    
    // 执行指令
    bool success = executeInstruction(instruction);
    
    if (success) {
        emit instructionExecuted(instruction);
        
        // 更新指令指针（除非指令本身修改了IP）
        if (instruction.mnemonic != "JMP" && 
            instruction.mnemonic != "JE" && 
            instruction.mnemonic != "JNE" && 
            instruction.mnemonic != "CALL") {
            instructionPointer++;
        }
    } else {
        currentState = CpuState::Error;
        emit stateChanged(currentState);
        emit errorOccurred(QString("指令执行失败: %1").arg(instruction.originalText));
    }
    
    return success;
}

/**
 * @brief 暂停执行
 */
void CpuSimulator::pauseExecution()
{
    QMutexLocker locker(&cpuMutex);
    if (currentState == CpuState::Running) {
        executionTimer->stop();
        currentState = CpuState::Paused;
        emit stateChanged(currentState);
    }
}

/**
 * @brief 继续执行
 */
void CpuSimulator::resumeExecution()
{
    QMutexLocker locker(&cpuMutex);
    if (currentState == CpuState::Paused) {
        currentState = CpuState::Running;
        emit stateChanged(currentState);
        executionTimer->start();
    }
}

/**
 * @brief 停止执行
 */
void CpuSimulator::stopExecution()
{
    QMutexLocker locker(&cpuMutex);
    executionTimer->stop();
    currentState = CpuState::Stopped;
    halted = false;
    emit stateChanged(currentState);
}

/**
 * @brief 重置CPU状态
 */
void CpuSimulator::resetCpu()
{
    QMutexLocker locker(&cpuMutex);
    
    currentState = CpuState::Stopped;
    instructionPointer = 0;
    halted = false;
    
    // 重置寄存器
    initializeRegisters();
    
    // 清空指令和标签
    instructions.clear();
    labels.clear();
    breakpoints.clear();
    
    // 重置内存（保留基本结构）
    initializeMemory();
    
    emit stateChanged(currentState);
}

/**
 * @brief 获取寄存器值
 * @param registerName 寄存器名称
 * @return int 寄存器值
 */
int CpuSimulator::getRegister(const QString& registerName) const
{
    QMutexLocker locker(&cpuMutex);
    return registers.value(registerName.toUpper(), 0);
}

/**
 * @brief 设置寄存器值
 * @param registerName 寄存器名称
 * @param value 要设置的值
 */
void CpuSimulator::setRegister(const QString& registerName, int value)
{
    QMutexLocker locker(&cpuMutex);
    QString regName = registerName.toUpper();
    
    if (REGISTER_NAMES.contains(regName)) {
        registers[regName] = value;
        
        // 特殊处理IP寄存器
        if (regName == "IP") {
            instructionPointer = value;
        }
        
        emit registerChanged(regName, value);
    }
}

/**
 * @brief 获取所有寄存器状态
 * @return QMap<QString, int> 寄存器名称到值的映射
 */
QMap<QString, int> CpuSimulator::getAllRegisters() const
{
    QMutexLocker locker(&cpuMutex);
    return registers;
}

/**
 * @brief 获取寄存器值（内部方法，不加锁）
 * @param registerName 寄存器名称
 * @return int 寄存器值
 */
int CpuSimulator::getRegisterInternal(const QString& registerName) const
{
    return registers.value(registerName.toUpper(), 0);
}

/**
 * @brief 设置寄存器值（内部方法，不加锁）
 * @param registerName 寄存器名称
 * @param value 要设置的值
 */
void CpuSimulator::setRegisterInternal(const QString& registerName, int value)
{
    QString regName = registerName.toUpper();
    
    if (REGISTER_NAMES.contains(regName)) {
        registers[regName] = value;
        
        // 特殊处理IP寄存器
        if (regName == "IP") {
            instructionPointer = value;
        }
    }
}

/**
 * @brief 读取内存值
 * @param address 内存地址
 * @return int 内存值
 */
int CpuSimulator::getMemory(int address) const
{
    QMutexLocker locker(&cpuMutex);
    if (address >= 0 && address < MEMORY_SIZE) {
        return memory.value(address, 0);
    }
    return 0;
}

/**
 * @brief 写入内存值
 * @param address 内存地址
 * @param value 要写入的值
 */
void CpuSimulator::setMemory(int address, int value)
{
    QMutexLocker locker(&cpuMutex);
    if (address >= 0 && address < MEMORY_SIZE) {
        memory[address] = value;
        emit memoryChanged(address, value);
    }
}

/**
 * @brief 获取标志寄存器值
 * @return int 标志寄存器值
 */
int CpuSimulator::getFlags() const
{
    return getRegister("FLAGS");
}

/**
 * @brief 设置标志寄存器值
 * @param flags 标志值
 */
void CpuSimulator::setFlags(int flags)
{
    setRegister("FLAGS", flags);
}

/**
 * @brief 检查特定标志位
 * @param flag 标志位
 * @return bool 标志位是否设置
 */
bool CpuSimulator::isFlagSet(CpuFlags flag) const
{
    return (getFlags() & static_cast<int>(flag)) != 0;
}

/**
 * @brief 设置特定标志位
 * @param flag 标志位
 * @param value 是否设置
 */
void CpuSimulator::setFlag(CpuFlags flag, bool value)
{
    int flags = getFlags();
    if (value) {
        flags |= static_cast<int>(flag);
    } else {
        flags &= ~static_cast<int>(flag);
    }
    setFlags(flags);
}

/**
 * @brief 获取CPU当前状态
 * @return CpuState CPU状态
 */
CpuState CpuSimulator::getState() const
{
    QMutexLocker locker(&cpuMutex);
    return currentState;
}

/**
 * @brief 获取当前指令指针
 * @return int 指令指针值
 */
int CpuSimulator::getInstructionPointer() const
{
    QMutexLocker locker(&cpuMutex);
    return instructionPointer;
}

/**
 * @brief 设置指令指针
 * @param ip 新的指令指针值
 */
void CpuSimulator::setInstructionPointer(int ip)
{
    QMutexLocker locker(&cpuMutex);
    instructionPointer = ip;
    setRegister("IP", ip);
}

/**
 * @brief 检查CPU是否停机
 * @return bool 是否停机
 */
bool CpuSimulator::isHalted() const
{
    QMutexLocker locker(&cpuMutex);
    return halted;
}

/**
 * @brief 触发中断
 * @param interruptNumber 中断号
 * @return bool 中断是否成功触发
 */
bool CpuSimulator::triggerInterrupt(int interruptNumber)
{
    QMutexLocker locker(&cpuMutex);
    emit interruptTriggered(interruptNumber);
    return true;
}

/**
 * @brief 设置中断管理器
 * @param manager 外部中断管理器指针
 */
void CpuSimulator::setInterruptManager(InterruptManager* manager)
{
    interruptManager = manager;
    qDebug() << "CpuSimulator: 设置外部中断管理器" << (manager ? "成功" : "为nullptr");
}

/**
 * @brief 解析汇编代码
 * @param assemblyCode 汇编代码
 * @return bool 解析是否成功
 */
bool CpuSimulator::parseAssemblyCode(const QString& assemblyCode)
{
    instructions.clear();
    labels.clear();
    
    QStringList lines = assemblyCode.split('\n');
    
    qDebug() << "开始解析汇编代码，共" << lines.size() << "行";
    
    for (int i = 0; i < lines.size(); ++i) {
        QString line = lines[i].trimmed();
        
        qDebug() << "正在处理第" << (i+1) << "行:" << line;
        
        // 跳过空行和注释
        if (line.isEmpty() || line.startsWith(';')) {
            qDebug() << "跳过空行或注释行";
            continue;
        }
        
        // 处理标签
        if (line.endsWith(':')) {
            QString label = line.left(line.length() - 1).trimmed();
            labels[label] = instructions.size();
            qDebug() << "找到标签:" << label << "地址:" << instructions.size();
            continue;
        }
        
        // 解析指令
        Instruction instruction = parseInstruction(line, i + 1);
        if (!instruction.mnemonic.isEmpty()) {
            instructions.append(instruction);
            qDebug() << "解析指令:" << instruction.mnemonic << "操作数:" << instruction.operands;
        } else {
            qDebug() << "跳过无效指令行:" << line;
        }
    }
    
    qDebug() << "解析完成，共" << instructions.size() << "条指令";
    return !instructions.isEmpty();
}

/**
 * @brief 解析单条指令
 * @param line 代码行
 * @param lineNumber 行号
 * @return Instruction 解析后的指令
 */
Instruction CpuSimulator::parseInstruction(const QString& line, int lineNumber)
{
    Instruction instruction;
    instruction.originalText = line;
    instruction.lineNumber = lineNumber;
    
    qDebug() << "解析指令行:" << line;
    
    // 移除注释
    QString cleanLine = line;
    int commentPos = cleanLine.indexOf(';');
    if (commentPos >= 0) {
        cleanLine = cleanLine.left(commentPos);
    }
    cleanLine = cleanLine.trimmed();
    
    qDebug() << "去除注释后:" << cleanLine;
    
    // 如果清理后的行为空，返回空指令
    if (cleanLine.isEmpty()) {
        qDebug() << "清理后为空行，返回空指令";
        return instruction;
    }
    
    // 解析助记符和操作数
    QStringList parts = cleanLine.split(QRegularExpression("\\s+"));
    if (parts.isEmpty()) {
        qDebug() << "分割后无内容";
        return instruction;
    }
    
    QString potentialMnemonic = parts[0].toUpper();
    qDebug() << "潜在的助记符:" << potentialMnemonic;
    
    // 检查是否是有效的汇编指令
    QStringList validInstructions = {"MOV", "ADD", "SUB", "MUL", "DIV", "CMP", "JMP", "JE", "JNE", "JL", "JG", "JLE", "JGE", 
                                    "PUSH", "POP", "CALL", "RET", "INT", "IRET", "HLT", "NOP", "AND", "OR", "XOR", "NOT", 
                                    "SHL", "SHR", "ROL", "ROR", "INC", "DEC", "LEA", "LOOP", "LOOPE", "LOOPNE", "TEST"};
    
    if (!validInstructions.contains(potentialMnemonic)) {
        qDebug() << "无效的汇编指令:" << potentialMnemonic << "，跳过此行";
        return instruction; // 返回空指令
    }
    
    instruction.mnemonic = potentialMnemonic;
    
    // 解析操作数
    if (parts.size() > 1) {
        QString operandStr = parts.mid(1).join(" ");
        instruction.operands = operandStr.split(',');
        for (QString& operand : instruction.operands) {
            operand = operand.trimmed();
        }
    }
    
    qDebug() << "成功解析指令:" << instruction.mnemonic << "操作数:" << instruction.operands;
    
    // 确定指令类型
    if (instruction.mnemonic == "MOV" || instruction.mnemonic == "LEA") {
        instruction.type = InstructionType::DataTransfer;
    } else if (instruction.mnemonic == "ADD" || instruction.mnemonic == "SUB" || 
               instruction.mnemonic == "MUL" || instruction.mnemonic == "DIV") {
        instruction.type = InstructionType::Arithmetic;
    } else if (instruction.mnemonic == "AND" || instruction.mnemonic == "OR" || 
               instruction.mnemonic == "XOR" || instruction.mnemonic == "NOT") {
        instruction.type = InstructionType::Logic;
    } else if (instruction.mnemonic == "JMP" || instruction.mnemonic == "JE" || 
               instruction.mnemonic == "JNE" || instruction.mnemonic == "CALL") {
        instruction.type = InstructionType::Control;
    } else if (instruction.mnemonic == "PUSH" || instruction.mnemonic == "POP") {
        instruction.type = InstructionType::Stack;
    } else if (instruction.mnemonic == "INT" || instruction.mnemonic == "IRET") {
        instruction.type = InstructionType::Interrupt;
    }
    
    return instruction;
}

/**
 * @brief 执行单条指令
 * @param instruction 要执行的指令
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeInstruction(const Instruction& instruction)
{
    QString mnemonic = instruction.mnemonic.toUpper();
    qDebug() << "执行指令:" << mnemonic << "操作数:" << instruction.operands;
    
    if (mnemonic == "MOV") {
        return executeMov(instruction.operands);
    } else if (mnemonic == "ADD") {
        return executeAdd(instruction.operands);
    } else if (mnemonic == "SUB") {
        return executeSub(instruction.operands);
    } else if (mnemonic == "MUL") {
        return executeMul(instruction.operands);
    } else if (mnemonic == "DIV") {
        return executeDiv(instruction.operands);
    } else if (mnemonic == "CMP") {
        return executeCmp(instruction.operands);
    } else if (mnemonic == "JMP") {
        return executeJmp(instruction.operands);
    } else if (mnemonic == "JE") {
        return executeJe(instruction.operands);
    } else if (mnemonic == "INT") {
        return executeInt(instruction.operands);
    } else if (mnemonic == "HLT") {
        return executeHlt(instruction.operands);
    } else if (mnemonic == "NOP") {
        // 空操作
        return true;
    }
    
    // 未知指令
    emit errorOccurred(QString("未知指令: %1").arg(mnemonic));
    return false;
}

/**
 * @brief 执行MOV指令
 * @param operands 操作数列表
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeMov(const QStringList& operands)
{
    qDebug() << "开始执行MOV指令，操作数数量:" << operands.size();
    
    if (operands.size() != 2) {
        qDebug() << "MOV指令操作数数量错误";
        return false;
    }
    
    QString dest = operands[0].trimmed();
    QString src = operands[1].trimmed();
    
    qDebug() << "MOV指令 - 目标:" << dest << "源:" << src;
    
    qDebug() << "开始解析源操作数:" << src;
    int value = parseOperand(src);
    qDebug() << "源操作数解析完成，值:" << value;
    
    qDebug() << "开始处理目标操作数:" << dest;
    
    if (isRegister(dest)) {
        qDebug() << "目标是寄存器:" << dest;
        
        // 先释放锁，然后调用setRegister（它会重新获取锁）
        QString regName = dest.toUpper();
        if (REGISTER_NAMES.contains(regName)) {
            qDebug() << "设置寄存器" << regName << "值为" << value;
            
            // 直接在锁内修改寄存器，但准备延迟发射信号
            registers[regName] = value;
            
            // 特殊处理IP寄存器
            if (regName == "IP") {
                instructionPointer = value;
            }
            
            qDebug() << "寄存器设置完成";
        } else {
            qDebug() << "无效的寄存器名:" << regName;
            return false;
        }
    } else if (isMemoryAddress(dest)) {
        qDebug() << "目标是内存地址:" << dest;
        int address = parseMemoryAddress(dest);
        qDebug() << "内存地址解析完成，地址:" << address;
        
        // 直接在锁内修改内存，信号发射在executeNextInstruction中处理
        if (address >= 0 && address < MEMORY_SIZE) {
            // 确保memory有足够大小
            while (memory.size() <= address) {
                memory.append(0);
            }
            memory[address] = value;
            qDebug() << "内存设置完成";
        } else {
            qDebug() << "无效的内存地址:" << address;
            return false;
        }
    } else {
        qDebug() << "无效的目标操作数:" << dest;
        return false;
    }
    
    qDebug() << "MOV指令执行完成";
    return true;
}

/**
 * @brief 执行ADD指令
 * @param operands 操作数列表
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeAdd(const QStringList& operands)
{
    qDebug() << "开始执行ADD指令，操作数数量:" << operands.size();
    
    if (operands.size() != 2) {
        qDebug() << "ADD指令操作数数量错误";
        return false;
    }
    
    QString dest = operands[0].trimmed();
    QString src = operands[1].trimmed();
    
    qDebug() << "ADD指令 - 目标:" << dest << "源:" << src;
    
    qDebug() << "解析目标操作数:" << dest;
    int destValue = parseOperand(dest);
    qDebug() << "目标值:" << destValue;
    
    qDebug() << "解析源操作数:" << src;
    int srcValue = parseOperand(src);
    qDebug() << "源值:" << srcValue;
    
    int result = destValue + srcValue;
    qDebug() << "计算结果:" << destValue << "+" << srcValue << "=" << result;
    
    if (isRegister(dest)) {
        qDebug() << "目标是寄存器:" << dest;
        QString regName = dest.toUpper();
        if (REGISTER_NAMES.contains(regName)) {
            qDebug() << "设置寄存器" << regName << "从" << registers.value(regName, 0) << "更新为" << result;
            
            // 直接在锁内修改寄存器，信号发射在executeNextInstruction中处理
            registers[regName] = result;
            
            // 特殊处理IP寄存器
            if (regName == "IP") {
                instructionPointer = result;
            }
            qDebug() << "寄存器" << regName << "更新完成，当前值:" << registers.value(regName, 0);
        } else {
            qDebug() << "无效的寄存器名:" << regName;
            return false;
        }
    } else if (isMemoryAddress(dest)) {
        qDebug() << "目标是内存地址:" << dest;
        int address = parseMemoryAddress(dest);
        qDebug() << "内存地址:" << address;
        
        // 直接在锁内修改内存，信号发射在executeNextInstruction中处理
        if (address >= 0 && address < MEMORY_SIZE) {
            // 确保memory有足够大小
            while (memory.size() <= address) {
                memory.append(0);
            }
            memory[address] = result;
            qDebug() << "内存更新完成";
        } else {
            qDebug() << "无效的内存地址:" << address;
            return false;
        }
    } else {
        qDebug() << "无效的目标操作数:" << dest;
        return false;
    }
    
    qDebug() << "更新标志位";
    updateFlags(result);
    qDebug() << "ADD指令执行完成";
    return true;
}

/**
 * @brief 执行SUB指令
 * @param operands 操作数列表
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeSub(const QStringList& operands)
{
    qDebug() << "开始执行SUB指令，操作数数量:" << operands.size();
    
    if (operands.size() != 2) {
        qDebug() << "SUB指令操作数数量错误";
        return false;
    }
    
    QString dest = operands[0].trimmed();
    QString src = operands[1].trimmed();
    
    qDebug() << "SUB指令 - 目标:" << dest << "源:" << src;
    
    qDebug() << "解析目标操作数:" << dest;
    int destValue = parseOperand(dest);
    qDebug() << "目标值:" << destValue;
    
    qDebug() << "解析源操作数:" << src;
    int srcValue = parseOperand(src);
    qDebug() << "源值:" << srcValue;
    
    int result = destValue - srcValue;
    qDebug() << "计算结果:" << destValue << "-" << srcValue << "=" << result;
    
    if (isRegister(dest)) {
        qDebug() << "目标是寄存器:" << dest;
        QString regName = dest.toUpper();
        if (REGISTER_NAMES.contains(regName)) {
            qDebug() << "设置寄存器" << regName << "从" << registers.value(regName, 0) << "更新为" << result;
            
            // 直接在锁内修改寄存器，信号发射在executeNextInstruction中处理
            registers[regName] = result;
            
            // 特殊处理IP寄存器
            if (regName == "IP") {
                instructionPointer = result;
            }
            qDebug() << "寄存器" << regName << "更新完成，当前值:" << registers.value(regName, 0);
        } else {
            qDebug() << "无效的寄存器名:" << regName;
            return false;
        }
    } else if (isMemoryAddress(dest)) {
        qDebug() << "目标是内存地址:" << dest;
        int address = parseMemoryAddress(dest);
        qDebug() << "内存地址:" << address;
        
        // 直接在锁内修改内存，信号发射在executeNextInstruction中处理
        if (address >= 0 && address < MEMORY_SIZE) {
            // 确保memory有足够大小
            while (memory.size() <= address) {
                memory.append(0);
            }
            memory[address] = result;
            qDebug() << "内存更新完成";
        } else {
            qDebug() << "无效的内存地址:" << address;
            return false;
        }
    } else {
        qDebug() << "无效的目标操作数:" << dest;
        return false;
    }
    
    qDebug() << "更新标志位";
    updateFlags(result);
    qDebug() << "SUB指令执行完成";
    return true;
}

/**
 * @brief 执行INT指令
 * @param operands 操作数列表
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeInt(const QStringList& operands)
{
    qDebug() << "开始执行INT指令，操作数数量:" << operands.size();
    
    if (operands.size() != 1) {
        qDebug() << "INT指令操作数数量错误";
        return false;
    }
    
    int interruptNumber = parseOperand(operands[0]);
    qDebug() << "解析得到中断号:" << interruptNumber << "(0x" << QString::number(interruptNumber, 16) << ")";
    
    // 为了避免死锁，我们需要临时创建一个CPU代理类，
    // 该类提供不加锁的寄存器访问方法
    class CpuProxy {
    private:
        CpuSimulator* cpu;
        
    public:
        CpuProxy(CpuSimulator* c) : cpu(c) {}
        
        int getRegister(const QString& name) const {
            return cpu->getRegisterInternal(name);
        }
        
        void setRegister(const QString& name, int value) {
            cpu->setRegisterInternal(name, value);
        }
        
        // 为了兼容现有代码，提供与CpuSimulator相同的接口
        int getMemory(int address) const {
            return cpu->getMemory(address);
        }
        
        void setMemory(int address, int value) {
            cpu->setMemory(address, value);
        }
    };
    
    // 创建代理对象
    CpuProxy proxy(this);
    
    // 使用中断管理器处理中断，但传递代理对象而不是this
    if (interruptManager && interruptManager->isInterruptSupported(interruptNumber)) {
        qDebug() << "中断管理器支持此中断号，开始处理";
        
        // 暂时解除锁，让中断处理器能够正常工作
        cpuMutex.unlock();
        
        // 注意：这里传递的是CpuProxy，不是this，以避免类型问题
        // 我们需要修改中断处理器的签名或者创建一个通用接口
        // 为了现在能工作，我们先传递this，但使用内部方法
        SystemCallResult result = interruptManager->handleInterrupt(interruptNumber, this);
        
        // 重新获取锁
        cpuMutex.lock();
        
        qDebug() << "中断处理完成，成功:" << result.success;
        
        if (result.success) {
            qDebug() << "中断处理成功，返回值数量:" << result.returnValues.size();
            // 直接操作寄存器，避免重复加锁
            for (auto it = result.returnValues.begin(); it != result.returnValues.end(); ++it) {
                QString regName = it.key().toUpper();
                if (REGISTER_NAMES.contains(regName)) {
                    qDebug() << "设置返回寄存器" << regName << "值为" << it.value();
                    registers[regName] = it.value();
                    
                    // 特殊处理IP寄存器
                    if (regName == "IP") {
                        instructionPointer = it.value();
                    }
                }
            }
        } else {
            qDebug() << "中断处理失败:" << result.errorMessage;
            return false;
        }
    } else {
        qDebug() << "不支持的中断号:" << interruptNumber;
        return false;
    }
    
    qDebug() << "INT指令执行完成";
    return true;
}

/**
 * @brief 执行HLT指令
 * @param operands 操作数列表
 * @return bool 执行是否成功
 */
bool CpuSimulator::executeHlt(const QStringList& operands)
{
    Q_UNUSED(operands)
    halted = true;
    return true;
}

/**
 * @brief 解析操作数
 * @param operand 操作数字符串
 * @return int 操作数值
 */
int CpuSimulator::parseOperand(const QString& operand)
{
    QString op = operand.trimmed();
    qDebug() << "解析操作数:" << op;
    
    if (isRegister(op)) {
        qDebug() << "操作数是寄存器:" << op;
        // 直接访问寄存器，避免重复加锁
        int value = registers.value(op.toUpper(), 0);
        qDebug() << "寄存器值:" << value;
        return value;
    } else if (isMemoryAddress(op)) {
        qDebug() << "操作数是内存地址:" << op;
        int address = parseMemoryAddress(op);
        qDebug() << "内存地址:" << address;
        // 直接访问内存，避免重复加锁
        if (address >= 0 && address < MEMORY_SIZE) {
            int value = memory.value(address, 0);
            qDebug() << "内存值:" << value;
            return value;
        }
        qDebug() << "无效内存地址，返回0";
        return 0;
    } else if (isImmediate(op)) {
        qDebug() << "操作数是立即数:" << op;
        // 处理立即数
        if (op.startsWith("$")) {
            op = op.mid(1);  // 移除$符号
        }
        
        bool ok;
        int value;
        
        if (op.startsWith("0x") || op.startsWith("0X")) {
            value = op.toInt(&ok, 16);  // 十六进制
            qDebug() << "十六进制立即数，转换结果:" << value << "成功:" << ok;
        } else if (op.startsWith("0b") || op.startsWith("0B")) {
            value = op.mid(2).toInt(&ok, 2);  // 二进制
            qDebug() << "二进制立即数，转换结果:" << value << "成功:" << ok;
        } else if (op.startsWith("0") && op.length() > 1) {
            value = op.toInt(&ok, 8);  // 八进制
            qDebug() << "八进制立即数，转换结果:" << value << "成功:" << ok;
        } else {
            value = op.toInt(&ok, 10);  // 十进制
            qDebug() << "十进制立即数，转换结果:" << value << "成功:" << ok;
        }
        
        return ok ? value : 0;
    }
    
    qDebug() << "无法识别的操作数类型，返回0";
    return 0;
}

/**
 * @brief 检查是否为寄存器名
 * @param name 名称
 * @return bool 是否为寄存器
 */
bool CpuSimulator::isRegister(const QString& name) const
{
    return REGISTER_NAMES.contains(name.toUpper());
}

/**
 * @brief 检查是否为立即数
 * @param operand 操作数
 * @return bool 是否为立即数
 */
bool CpuSimulator::isImmediate(const QString& operand) const
{
    QString op = operand.trimmed();
    return op.startsWith("$") || op.contains(QRegularExpression("^[0-9]"));
}

/**
 * @brief 检查是否为内存地址
 * @param operand 操作数
 * @return bool 是否为内存地址
 */
bool CpuSimulator::isMemoryAddress(const QString& operand) const
{
    QString op = operand.trimmed();
    return op.startsWith("[") && op.endsWith("]");
}

/**
 * @brief 解析内存地址
 * @param address 地址字符串
 * @return int 内存地址
 */
int CpuSimulator::parseMemoryAddress(const QString& address)
{
    QString addr = address.trimmed();
    qDebug() << "解析内存地址:" << addr;
    
    if (addr.startsWith("[") && addr.endsWith("]")) {
        addr = addr.mid(1, addr.length() - 2);  // 移除[]
        qDebug() << "移除[]后的地址内容:" << addr;
        
        // 避免无限递归，直接解析地址内容而不调用parseOperand
        addr = addr.trimmed();
        
        if (isRegister(addr)) {
            // 如果是寄存器，返回寄存器的值作为地址
            int value = registers.value(addr.toUpper(), 0);
            qDebug() << "地址来自寄存器" << addr << "值:" << value;
            return value;
        } else if (isImmediate(addr)) {
            // 如果是立即数，直接解析为地址
            if (addr.startsWith("$")) {
                addr = addr.mid(1);  // 移除$符号
            }
            
            bool ok;
            int value;
            
            if (addr.startsWith("0x") || addr.startsWith("0X")) {
                value = addr.toInt(&ok, 16);  // 十六进制
            } else if (addr.startsWith("0b") || addr.startsWith("0B")) {
                value = addr.mid(2).toInt(&ok, 2);  // 二进制
            } else if (addr.startsWith("0") && addr.length() > 1) {
                value = addr.toInt(&ok, 8);  // 八进制
            } else {
                value = addr.toInt(&ok, 10);  // 十进制
            }
            
            qDebug() << "地址立即数解析结果:" << value << "成功:" << ok;
            return ok ? value : 0;
        } else {
            qDebug() << "无法识别的地址内容:" << addr;
            return 0;
        }
    }
    qDebug() << "无效的内存地址格式";
    return 0;
}

/**
 * @brief 更新标志位
 * @param result 运算结果
 */
void CpuSimulator::updateFlags(int result)
{
    // 直接操作FLAGS寄存器，避免重复加锁
    int flags = registers.value("FLAGS", 0);
    
    // 零标志位
    if (result == 0) {
        flags |= static_cast<int>(CpuFlags::Zero);
    } else {
        flags &= ~static_cast<int>(CpuFlags::Zero);
    }
    
    // 符号标志位
    if (result < 0) {
        flags |= static_cast<int>(CpuFlags::Sign);
    } else {
        flags &= ~static_cast<int>(CpuFlags::Sign);
    }
    
    // 简化的奇偶校验位
    int bits = 0;
    int temp = result;
    while (temp) {
        bits += temp & 1;
        temp >>= 1;
    }
    if ((bits % 2) == 0) {
        flags |= static_cast<int>(CpuFlags::Parity);
    } else {
        flags &= ~static_cast<int>(CpuFlags::Parity);
    }
    
    // 直接设置FLAGS寄存器
    registers["FLAGS"] = flags;
}

/**
 * @brief 初始化寄存器
 */
void CpuSimulator::initializeRegisters()
{
    registers.clear();
    for (const QString& regName : REGISTER_NAMES) {
        registers[regName] = 0;
    }
    
    // 设置栈指针
    registers["SP"] = STACK_BASE;
}

/**
 * @brief 初始化内存
 */
void CpuSimulator::initializeMemory()
{
    memory.clear();
    // 内存按需分配，不预先初始化所有地址
}

// 占位实现其他指令
bool CpuSimulator::executeMul(const QStringList& operands) { Q_UNUSED(operands) return true; }
bool CpuSimulator::executeDiv(const QStringList& operands) { Q_UNUSED(operands) return true; }
bool CpuSimulator::executeCmp(const QStringList& operands) { Q_UNUSED(operands) return true; }
bool CpuSimulator::executeJmp(const QStringList& operands) { Q_UNUSED(operands) return true; }
bool CpuSimulator::executeJe(const QStringList& operands) { Q_UNUSED(operands) return true; }

// 占位实现其他方法
QList<int> CpuSimulator::getMemoryRange(int startAddress, int size) const { Q_UNUSED(startAddress) Q_UNUSED(size) return {}; }
void CpuSimulator::setMemoryRange(int startAddress, const QList<int>& values) { Q_UNUSED(startAddress) Q_UNUSED(values) }
Instruction CpuSimulator::getCurrentInstruction() const { return Instruction(); }
QList<Instruction> CpuSimulator::getInstructions() const { 
    QMutexLocker locker(&cpuMutex);
    return instructions; 
}
int CpuSimulator::getProgramSize() const { 
    QMutexLocker locker(&cpuMutex);
    return instructions.size(); 
}
void CpuSimulator::setBreakpoint(int lineNumber) { breakpoints.insert(lineNumber); }
void CpuSimulator::clearBreakpoint(int lineNumber) { breakpoints.remove(lineNumber); }
bool CpuSimulator::hasBreakpoint(int lineNumber) const { return breakpoints.contains(lineNumber); }
int CpuSimulator::findLabelAddress(const QString& label) { return labels.value(label, -1); }
void CpuSimulator::clearAllBreakpoints() { breakpoints.clear(); }

/**
 * @brief 执行下一条指令 (计时器槽函数)
 */
void CpuSimulator::executeNextInstruction()
{
    QMutexLocker locker(&cpuMutex);
    
    qDebug() << "executeNextInstruction 开始 - 当前指令指针:" << instructionPointer << "状态:" << static_cast<int>(currentState);
    
    // 检查是否应该停止执行
    if (currentState != CpuState::Running || halted || instructionPointer >= instructions.size()) {
        executionTimer->stop();
        
        qDebug() << "执行停止条件检查 - 运行状态:" << (currentState == CpuState::Running) 
                 << "未停机:" << (!halted) << "指令范围内:" << (instructionPointer < instructions.size());
        
        if (halted) {
            currentState = CpuState::Halted;
            qDebug() << "CPU已停机";
        } else if (instructionPointer >= instructions.size()) {
            currentState = CpuState::Stopped;
            qDebug() << "程序执行完成";
        }
        
        // 使用QTimer::singleShot延迟发射信号，避免死锁
        QTimer::singleShot(0, this, [this]() {
            emit stateChanged(currentState);
            // 程序执行完成时触发界面更新
            emit instructionExecuted(Instruction());  // 空指令表示执行完成
        });
        return;
    }
    
    // 检查断点
    if (hasBreakpoint(instructions[instructionPointer].lineNumber)) {
        executionTimer->stop();
        currentState = CpuState::Paused;
        qDebug() << "遇到断点，暂停执行";
        
        // 使用延迟发射避免死锁
        QTimer::singleShot(0, this, [this]() {
            emit stateChanged(currentState);
            emit breakpointHit(instructions[instructionPointer].lineNumber);
        });
        return;
    }
    
    const Instruction& instruction = instructions[instructionPointer];
    
    qDebug() << "准备执行指令:" << instruction.mnemonic << "操作数:" << instruction.operands;
    
    // 记录执行前的寄存器状态，用于检测变更
    QMap<QString, int> oldRegisters = registers;
    QMap<int, int> oldMemory;
    for (int i = 0; i < 256; i++) {  // 扩大检测范围到前256个内存位置，包含地址100-105
        if (memory.size() > i) {
            oldMemory[i] = memory[i];
        }
    }
    
    // 执行指令
    bool success = executeInstruction(instruction);
    
    qDebug() << "指令执行结果:" << success;
    
    if (success) {
        // 使用延迟发射避免死锁
        QTimer::singleShot(0, this, [this, instruction]() {
            emit instructionExecuted(instruction);
        });
        
        // 检测寄存器变更并发射信号
        for (auto it = registers.begin(); it != registers.end(); ++it) {
            if (oldRegisters.value(it.key(), 0) != it.value()) {
                qDebug() << "寄存器" << it.key() << "从" << oldRegisters.value(it.key(), 0) << "变更为" << it.value();
                
                // 使用延迟发射registerChanged信号
                QString regName = it.key();
                int newValue = it.value();
                QTimer::singleShot(0, this, [this, regName, newValue]() {
                    emit registerChanged(regName, newValue);
                });
            }
        }
        
        // 检测内存变更并发射信号
        for (int i = 0; i < 256; i++) {  // 扩大检测范围到前256个内存位置
            int oldValue = oldMemory.value(i, 0);
            int newValue = (memory.size() > i) ? memory[i] : 0;
            if (oldValue != newValue) {
                qDebug() << "内存地址" << i << "从" << oldValue << "变更为" << newValue;
                
                // 使用延迟发射memoryChanged信号
                QTimer::singleShot(0, this, [this, i, newValue]() {
                    emit memoryChanged(i, newValue);
                });
            }
        }
        
        // 更新指令指针（除非指令本身修改了IP）
        if (instruction.mnemonic != "JMP" && 
            instruction.mnemonic != "JE" && 
            instruction.mnemonic != "JNE" && 
            instruction.mnemonic != "CALL") {
            instructionPointer++;
            qDebug() << "指令指针更新为:" << instructionPointer;
        }
    } else {
        executionTimer->stop();
        currentState = CpuState::Error;
        qDebug() << "指令执行失败，停止执行";
        
        // 使用延迟发射避免死锁
        QTimer::singleShot(0, this, [this, instruction]() {
            emit stateChanged(currentState);
            emit errorOccurred(QString("指令执行失败: %1").arg(instruction.originalText));
        });
    }
    
    qDebug() << "executeNextInstruction 执行完成";
} 
